package com.example.demo.web;

import com.alibaba.fastjson.JSON;
import com.example.demo.mapper.firstsqlserver.ProjectMapper;
import com.example.demo.pojo.Project;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class ProjectController {

    @Autowired
    private ProjectMapper projectMapper;

    @RequestMapping("/project")
    public String project(Model model, @RequestParam(value = "start", defaultValue = "1")int start, @RequestParam(value = "size", defaultValue = "6")int size) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String now = sdf.format(new Date());
        PageHelper.startPage(start, size);
        List<Project> projects = projectMapper.listProject(now);
        int count = projects.size();
        int sucs = 0;
        for (Project project : projects) {
            sucs += project.getSuccess();
        }
        PageInfo<Project> pager = new PageInfo<>(projects);
        String data = JSON.toJSONString(pager.getList());
        model.addAttribute("now", now);
        model.addAttribute("count", count);
        model.addAttribute("sucs", sucs);
        model.addAttribute("data", data);
        return "project";
    }

    @ResponseBody
    @RequestMapping("/getProjectData")
    public List<Project> getProjectData(@RequestParam("date")String date, @RequestParam(value = "start", defaultValue = "1")int start, @RequestParam(value = "size", defaultValue = "6")int size) {
        List<Project> projects = projectMapper.listProject(date);
        int count = projects.size();
        int sucs = 0;
        for (Project project : projects) {
            sucs += project.getSuccess();
        }
        PageHelper.startPage(start, size);
        List<Project> pager = projectMapper.listProject(date);
        for (Project project : pager) {
            project.setCount(count);
            project.setSucs(sucs);
        }
        PageInfo<Project> pageInfo = new PageInfo<>(pager);
        return pageInfo.getList();
    }
}
